package com.cn;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description : 自定义线程工厂-自定义线程名称
 * @Author : Bruce Lee
 * @CreateTime : 2024/5/28
 */

public class NamedThreadFactory implements ThreadFactory {

    // 线程池名称前缀
    private String name;

    // 线程池编号
    private static final AtomicInteger poolNumber = new AtomicInteger(1);

    // 线程编号(注意区别于线程池编号)
    private static final AtomicInteger threadNumber = new AtomicInteger(1);

    /**
     * 线程池创建时，该构造函数只会调用一次，所以线程池编号只会增加一次
     * @param namePrefix
     */
    public NamedThreadFactory(String namePrefix) {

        this.name = namePrefix +"-"+
                poolNumber.getAndIncrement() +
                "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, name + threadNumber.getAndIncrement());
        // 线程池默认创建的Worker线程是“非守护线程”
//        thread.setDaemon(true);
        return thread;
    }
}
